"""
难度：简单
给定一个二叉树，返回它的 后序 遍历。
示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]
进阶: 递归算法很简单，你可以通过迭代算法完成吗？
"""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        
        def dfs(root):
            if not root:
                return 
            dfs(root.left)
            dfs(root.right)
            res.append(root.val)
        dfs(root)

        return res
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        stack = []
        prev = None

        while root or len(stack) != 0 :
            while root:
                stack.append(root)
                root = root.left
            root = stack[-1]
            if root.right == None or root.right == prev:
                res.append(root.val)
                stack.pop()
                prev = root
                root = None
            else:
                root = root.right
                
        return res


            